import traceback
from flask import Flask, request, jsonify
from docx_reader import ThesisProcessor
# from template_reader import TemplateProcessor
import db_utils
import os

UPLOAD_FOLDER = "uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["JSON_AS_ASCII"] = False

@app.route("/uploadPaper", methods=["POST"])
def upload_file():
    try:
        print("接收到上传请求")
        print("请求表单数据:", request.form)
        print("请求文件数据:", request.files)

        # 检查文件是否存在
        if "file" not in request.files:
            print("错误：没有找到文件字段 'file'")
            return jsonify({"error": "没有文件"}), 400

        file = request.files["file"]
        print("上传的文件名:", file.filename)

        # 获取 upload_id
        upload_id = request.form.get('upload_id', '')
        upload_id = int(upload_id) if upload_id else None
        print("upload_id:", upload_id)

        # 保存文件
        save_path = os.path.join(app.config["UPLOAD_FOLDER"], file.filename)
        file.save(save_path)
        print("文件已保存到:", save_path)

        # 处理文档
        processor = ThesisProcessor()
        result = processor.process_document(save_path)
        print("文档处理结果:", result)

        info = result.get("info", {})
        print("解析出的论文信息:", info)

        # 校验教师和学生信息
        teacher2 = db_utils.get_userId(info.get("teacher2"))
        teacher2 = teacher2 if teacher2 is not False else None
        student_valid = db_utils.validate_student(
            info.get("number"),
            info.get("author"),
            db_utils.get_majorId(info.get("major")),
            db_utils.get_userId(info.get("teacher1")),
            teacher2
        )
        print("学生信息校验结果:", student_valid)

        if not student_valid:
            print("错误：学生信息不匹配，禁止入库")
            return jsonify({"error": "学生信息不匹配，禁止入库"}), 400

        # 保存到数据库
        paper_id = db_utils.save_paper_to_db(result, upload_id, save_path)
        print("论文已成功保存，paper_id:", paper_id)

        data = {
            "message": "上传成功",
            "paper_id": paper_id,
            "title": info.get("title"),
            "author": info.get("author")
        }
        return jsonify(data)

    except Exception as e:
        print("上传或处理过程中发生异常:", e)
        traceback.print_exc()
        return jsonify({"message": "上传失败", "error": str(e)}), 500

if __name__ == "__main__":
    print("Flask 服务启动中，监听端口 5001...")
    app.run(host="0.0.0.0", port=5001, debug=True)
